package com.wlf.util;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

/**
 * 微信调用接口公共类
 *
 * @author King
 *
 */
public class HttpClientUtil {

	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

	/**
	 * Get方式获取数据
	 *
	 * @param url
	 * @param valueType
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T doGet(String url, Class<T> valueType) {

		HttpClientBuilder build = HttpClientBuilder.create();

		build.setMaxConnTotal(10);
		build.setMaxConnPerRoute(10);

		HttpClient client = build.build();
		HttpGet get = new HttpGet(url);

		try {
			HttpResponse response;
			response = client.execute(get);
			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() != HttpStatus.SC_OK) {
				logger.error("请求微信链接时发生异常,响应码：" + status.getStatusCode());
			} else {
				if (valueType.equals(String.class)) {
					return (T) EntityUtils.toString(response.getEntity());
				}
				InputStream stream = response.getEntity().getContent();
				ObjectMapper mapper = new ObjectMapper();
				mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
				T t = mapper.readValue(stream, valueType);
				return t;
			}

		} catch (ClientProtocolException e) {
			logger.error("请求微信链接时发生异常:{}", e);
		} catch (IOException e) {
			logger.error("请求微信链接时发生异常:{}", e);
		} finally {
			get.releaseConnection();
		}

		return null;
	}

	public static String doGet(String url) {
		HttpClientBuilder build = HttpClientBuilder.create();

		build.setMaxConnTotal(10);
		build.setMaxConnPerRoute(10);

		HttpClient client = build.build();
		HttpGet get = new HttpGet(url);
		try {
			HttpResponse response;
			response = client.execute(get);
			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() != HttpStatus.SC_OK) {
				logger.error("请求微信链接时发生异常,响应码：" + status.getStatusCode());
			} else {
				return EntityUtils.toString(response.getEntity());
			}

		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		} finally {
			get.releaseConnection();
		}

		return null;
	}

	/**
	 * POST方式 获取数据
	 *
	 * @param url
	 * @param content
	 * @param valueType
	 * @return
	 */
	public static <T> T doPost(String url, Object content, Class<T> valueType) {

		StringWriter out = new StringWriter();
		ObjectMapper mapper = new ObjectMapper();
		JsonGenerator generator;
		try {
			generator = new JsonFactory().createGenerator(out);
			mapper.writeValue(generator, content);

		} catch (IOException e) {
			logger.error("转换对象时发生错误");
		} finally {
			IOUtils.closeQuietly(out);
		}

		HttpClientBuilder build = HttpClientBuilder.create();

		build.setMaxConnTotal(10);
		build.setMaxConnPerRoute(10);

		HttpClient client = build.build();
		HttpPost post = new HttpPost(url);
		post.setEntity(new StringEntity(out.toString(), "UTF-8"));
		HttpResponse response;

		try {
			response = client.execute(post);
			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() != HttpStatus.SC_OK) {
				logger.error("请求微信链接时发生异常,响应码：" + status.getStatusCode());
			} else {

				InputStream stream = response.getEntity().getContent();
				ObjectMapper mapperout = new ObjectMapper();
				mapperout.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
				T t = mapperout.readValue(stream, valueType);
				return t;
			}

		} catch (ClientProtocolException e) {
			logger.error("请求微信链接时发生异常:{}", e);
		} catch (IOException e) {
			logger.error("请求微信链接时发生异常:{}", e);
		} finally {
			post.releaseConnection();
		}

		return null;

	}

	/**
	 * post请求（用于请求json格式的参数）
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, String params) throws Exception {
		logger.info("[ HTTP-POST ]:{}, params:{}" , url, params);
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000*60).setConnectTimeout(1000*10).build();//设置请求和传输超时时间
		httpPost.setConfig(requestConfig);
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Content-Type", "application/json");
		String charSet = "UTF-8";
		StringEntity entity = new StringEntity(params, charSet);
		httpPost.setEntity(entity);
		CloseableHttpResponse response = null;

		try {

			response = httpclient.execute(httpPost);
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			logger.info("[HTTP-POST--RESPONSE-STATUS]:{}", status);
			if (state == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
				return jsonString;
			}
			else{
				throw new Exception("调用外部系统异常"+state);
			}
		}
		finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
